package com.ruyuan.dependency.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruyuan.dependency.order.entity.Order;
import com.ruyuan.dependency.order.mapper.OrderMapper;
import com.ruyuan.dependency.order.service.OrderService;
import com.ruyuan.dependency.order.vo.QueryOrderRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zhonghuashishan
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Order queryById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public List<Order> queryList(QueryOrderRequest request) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(request.getUserId())) {
            queryWrapper.eq("user_id", request.getUserId());
        }
        if (Objects.nonNull(request.getSkuId())) {
            queryWrapper.eq("sku_id", request.getSkuId());
        }
        if (Objects.nonNull(request.getType())) {
            queryWrapper.eq("type", request.getType());
        }
        if (Objects.nonNull(request.getStatus())) {
            queryWrapper.eq("status", request.getStatus());
        }
        if (StringUtils.isNotBlank(request.getMinCreateTime())) {
            queryWrapper.ge("create_time", request.getMinCreateTime());
        }

        return orderMapper.selectList(queryWrapper);
    }

    @Override
    public void save(Order order) {
        order.setCreateTime(new Date());
        order.setUpdateTime(order.getCreateTime());
        orderMapper.insert(order);
    }

    @Override
    public void updataStatus(Long orderId, String oldStatus, String newStatus) {
        Order order = Order.builder().status(newStatus).build();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", orderId);
        queryWrapper.eq("status", oldStatus);
        orderMapper.update(order, queryWrapper);
    }
}